<template>
  <div
    class="price"
    :style="priceStyle"
    :class="customClass"
  >
    <span
      v-if="beforeText"
      class="price-before-text"
    >{{ beforeText }}</span>
    <span
      v-if="currency && price"
      class="price-currency"
    >{{ currency }}</span>
    <span
      v-if="price"
      class="price-integer"
    >{{ price.integer }}</span>
    <span
      v-if="price && decimal>0"
      class="price-decimal"
    >{{ price.decimal }}</span>
    <span
      v-if="priceText"
      class="price-text"
    >{{ priceText }}</span>
    <span
      v-if="afterText"
      class="price-after-text"
    >{{ afterText }}</span>
  </div>
</template>

<script>
export default {
  name: 'CurrencyPrice',
  props: {
    currency: {
      type: [
        String, Boolean
      ],
      default: '¥'
    },
    beforeText: {
      type: String,
      default: ''
    },
    afterText: {
      type: String,
      default: ''
    },
    decimal: {
      type: [
        Number, Boolean
      ],
      default: 2
    },
    value: {
      type: [
        Number, String
      ],
      default: ''
    },
    color: {
      type: String,
      default: ''
    },
    customClass: {
      type: String
    }
  },
  data () {
    return {
      priceText: ''
    }
  },
  computed: {
    priceStyle () {
      if (this.color) {
        return `color: ${this.color}`
      }
      return ''
    },
    price () {
      let priceNumber = this.value
      if (typeof this.value === 'string') {
        priceNumber = priceNumber.replace(/[^\d.]/gi, '')
      }
      var price = parseFloat(priceNumber)
      if (isNaN(price)) {
        return null
      }
      if (this.decimal === false) {
        return {
          integer: price,
          decimal: 0
        }
      }
      var priceArr = price.toFixed(this.decimal).toString().split('.')
      return {
        integer: priceArr[0],
        decimal: priceArr[1]
      }
    }
  },
  mounted () {
    if (typeof this.value === 'string') {
      this.priceText = this.value.replace(/[0-9.]/g, '')
    }
  }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.price {
  display: inline-flex;
  align-items: flex-end;
  line-height: 1;
  font-family: Avenir-Heavy, PingFang SC, Helvetica Neue, Arial, sans-serif;
  font-size: 1em;
  font-weight: normal;
  &-currency {
    padding-right: 1px;
  }
  &-integer {
    font-size: 1.3em;
  }
  &-decimal {
    &::before {
      content: ".";
    }
  }
  &-text,
  &-after-text {
    margin-left: 2px;
    color: #bbb;
    align-self: center;
  }
  &-before-text {
    margin-right: 2px;
    color: #bbb;
  }
}
</style>
